package com.ybkj.daijia.api.gexin;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.IQueryResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.google.gson.Gson;
import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.server.model.Driver;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GeTuiEmployV4 {

    private static final Logger logger = LoggerFactory
        .getLogger(GeTuiEmployV4.class);

    private static String Host = "http://sdk.open.api.igexin.com/apiex.htm";

    private static String Host2 = "http://sdk.open.api.igexin.com/api.htm";

    public static void push(Driver driver, PushDataV4 pushDataV4,
        Setting setting) throws IOException {

        String userId = driver.getUserID();

        String AppID = setting.getGetuiAppID();
        String AppKey = setting.getGetuiAppKey();
        String Master = setting.getGetuiMaster();
        // 通用版
        String AppIDGeneral = setting.getGetuiAppIDGeneral();
        String AppKeyGeneral = setting.getGetuiAppKeyGeneral();
        String MasterGeneral = setting.getGetuiMasterGeneral();

        if (StringUtils.isNotBlank(AppID) && StringUtils.isNotBlank(AppKey)
            && StringUtils.isNotBlank(Master)) {
            IGtPush push = new IGtPush(Host, AppKey, Master);
            push.connect();

            SingleMessage message = new SingleMessage();
            message.setOffline(true);
            // 离线有效时间，单位为毫秒
            message.setOfflineExpireTime(1 * 3600 * 1000);

            Target target1 = new Target();

            target1.setAppId(AppID);
            target1.setClientId(userId);

            if (Driver.DEVICE_ANDRIOD.equals(driver.getDeviceType())) {
                TransmissionTemplate template = TransmissionTemplateDemo(
                    pushDataV4, AppID, AppKey);
                message.setData(template);
            } else if (Driver.DEVICE_IOS.equals(driver.getDeviceType())) {
                // TransmissionTemplate template =
                // TransmissionTemplateDemo(pushDataV4,AppIDGeneral,AppKeyGeneral);
                // message.setData(template);
            } else {
                // TODO 其他设备的推送
                if (StringUtils.isNotBlank(driver.getDeviceType())) {
                    logger.warn("This DeviceType:{} not support yet.", driver.getDeviceType());
                }
            }
            try {

                // logger.debug("getui startpush time : " + new Date());

                IPushResult ret = push.pushMessageToSingle(message, target1);

                // logger.debug("getui endpush time : " + new Date());
                logger.debug("push response : " + ret.getResponse().toString());

            } catch (Exception e) {
                logger.error("{}", e);
            }
        }
        // 通用版
        if (StringUtils.isNotBlank(AppIDGeneral)
            && StringUtils.isNotBlank(AppKeyGeneral)
            && StringUtils.isNotBlank(MasterGeneral)) {
            IGtPush push = new IGtPush(Host, AppKeyGeneral, MasterGeneral);
            push.connect();

            SingleMessage message = new SingleMessage();
            message.setOffline(true);
            // 离线有效时间，单位为毫秒
            message.setOfflineExpireTime(1 * 3600 * 1000);

            Target target1 = new Target();

            target1.setAppId(AppIDGeneral);
            target1.setClientId(userId);
            if (Driver.DEVICE_IOS.equals(driver.getDeviceType())) {
                TransmissionTemplate template = TransmissionTemplateDemo(
                    pushDataV4, AppIDGeneral, AppKeyGeneral);
                message.setData(template);
            } else {
                // TODO 其他设备的推送
                if (StringUtils.isNotBlank(driver.getDeviceType())) {
                    logger.warn("This DeviceType:{} not support yet.",
                        driver.getDeviceType());
                }
            }
            try {

                // logger.debug("getui startpush time : " + new Date());

                IPushResult ret = push.pushMessageToSingle(message, target1);

                // logger.debug("getui endpush time : " + new Date());
                logger.debug("push response : " + ret.getResponse().toString());

            } catch (Exception e) {
                logger.error("{}", e);
            }
        }

    }

    public static void message(Driver driver, String title, String text,
        Setting setting) throws IOException {

        String userId = driver.getUserID();

        String AppID = setting.getGetuiAppID();
        String AppKey = setting.getGetuiAppKey();
        String Master = setting.getGetuiMaster();
        // 通用版
        String AppIDGeneral = setting.getGetuiAppIDGeneral();
        String AppKeyGeneral = setting.getGetuiAppKeyGeneral();
        String MasterGeneral = setting.getGetuiMasterGeneral();

        if (StringUtils.isNotBlank(AppID) && StringUtils.isNotBlank(AppKey)
            && StringUtils.isNotBlank(Master)) {
            IGtPush push = new IGtPush(Host, AppKey, Master);
            push.connect();

            NotificationTemplate template = NotificationTemplateDemo(title,
                text, AppID, AppKey);
            SingleMessage message = new SingleMessage();
            message.setOffline(true);

            message.setOfflineExpireTime(1 * 3600 * 1000);
            message.setData(template);

            Target target1 = new Target();

            target1.setAppId(AppID);
            target1.setClientId(userId);

            try {
                if (Driver.DEVICE_ANDRIOD.equals(driver.getDeviceType())) {
                    IPushResult ret = push
                        .pushMessageToSingle(message, target1);
                    logger.debug("message response : "
                        + ret.getResponse().toString());
                }

            } catch (Exception e) {
                logger.error("{}", e);
            }
        }
        // 通用版
        if (StringUtils.isNotBlank(AppIDGeneral)
            && StringUtils.isNotBlank(AppKeyGeneral)
            && StringUtils.isNotBlank(MasterGeneral)) {
            IGtPush push = new IGtPush(Host, AppKeyGeneral, MasterGeneral);
            push.connect();

            NotificationTemplate template = NotificationTemplateDemo(title,
                text, AppIDGeneral, AppKeyGeneral);
            SingleMessage message = new SingleMessage();
            message.setOffline(true);

            message.setOfflineExpireTime(1 * 3600 * 1000);
            message.setData(template);

            Target target1 = new Target();

            target1.setAppId(AppIDGeneral);
            target1.setClientId(userId);

            try {

                if (Driver.DEVICE_IOS.equals(driver.getDeviceType())) {
                    IPushResult ret = push
                        .pushMessageToSingle(message, target1);
                    logger.debug("message response : "
                        + ret.getResponse().toString());
                }

            } catch (Exception e) {
                logger.error("{}", e);
            }
        }

    }

    public static TransmissionTemplate TransmissionTemplateDemo(
        PushDataV4 pushDataV4, String AppID, String AppKey) {

        Gson gson = new Gson();

        Map<String, String> extra = pushDataV4.getExtra();

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("code", pushDataV4.getCode());
        data.put("type", pushDataV4.getType());
        data.put("data", pushDataV4.getData());
        data.put("time", pushDataV4.getTime());
        data.put("sound", pushDataV4.getSound());
        if (pushDataV4.getCode().equals("0X10")) {
            data.put("extra", extra);
        }

        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(AppID);
        template.setAppkey(AppKey);
        // template.setTransmissionType(1);//强制启动应用
        template.setTransmissionType(2);// 等待应用启动

        template.setTransmissionContent(gson.toJson(data));

        String sound = "default";
        if (StringUtils.isNotBlank(pushDataV4.getSound())) {
            sound = pushDataV4.getSound();
        }

        String content = extra.get("content");
        if (StringUtils.isNotBlank(content) && content.length() > 40) {
            content = content.substring(0, 40) + "...";
        }

        APNPayload payload = new APNPayload();
        payload.setBadge(0);
        payload.setContentAvailable(1);
        payload.setSound(sound + ".mp3");
        // payload.setCategory("$由客户端定义");
        // 简单模式APNPayload.SimpleMsg
        payload.setAlertMsg(new APNPayload.SimpleAlertMsg(content));
        template.setAPNInfo(payload);

        return template;

    }

    public static NotificationTemplate NotificationTemplateDemo(String title,
        String text, String AppID, String AppKey) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(AppID);
        template.setAppkey(AppKey);

        // 设置通知栏标题与内容
        template.setTitle(title);
        template.setText(text);
        // 配置通知栏图标
        template.setLogo("lg_launcher.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);

        template.setTransmissionType(1);

        return template;
    }

    public static String getClientStatus(String userId, Setting setting)
        throws IOException {

        String AppID = setting.getGetuiAppID();
        String AppKey = setting.getGetuiAppKey();
        String Master = setting.getGetuiMaster();
        try {

            IGtPush push = new IGtPush(Host, AppKey, Master);
            IQueryResult abc = push.getClientIdStatus(AppID, userId);
            String result = abc.getResponse().get("result").toString();
            return result;

        } catch (Exception e) {
            logger.error("{}", e);
            return "Error";
        }

    }

    public static String getClientStatusGeneral(String userId, Setting setting)
        throws IOException {

        // 通用版
        String AppIDGeneral = setting.getGetuiAppIDGeneral();
        String AppKeyGeneral = setting.getGetuiAppKeyGeneral();
        String MasterGeneral = setting.getGetuiMasterGeneral();
        try {

            // 通用版
            IGtPush push = new IGtPush(Host, AppKeyGeneral, MasterGeneral);
            IQueryResult abc = push.getClientIdStatus(AppIDGeneral, userId);
            String result = abc.getResponse().get("result").toString();

            return result;

        } catch (Exception e) {
            logger.error("{}", e);
            return "Error";
        }

    }

    public static boolean getClientOnline(String userId, Setting setting) {

        boolean online = false;

        String AppID = setting.getGetuiDriverAppID();
        String AppKey = setting.getGetuiDriverAppKey();
        String Master = setting.getGetuiDriverMaster();
        // 通用版
        String AppIDGeneral = setting.getGetuiAppIDGeneral();
        String AppKeyGeneral = setting.getGetuiAppKeyGeneral();
        String MasterGeneral = setting.getGetuiMasterGeneral();
        if (StringUtils.isNotBlank(AppID) && StringUtils.isNotBlank(AppKey)
            && StringUtils.isNotBlank(Master)) {
            try {

                IGtPush push = new IGtPush(Host, AppKey, Master);
                IQueryResult abc = push.getClientIdStatus(AppID, userId);

                String result = abc.getResponse().get("result").toString();

                if (result.equals("Online")) {// 推送非在线
                    online = true;
                }

            } catch (Exception e) {
                logger.error("{}", e);
            }
        }
        // 通用版
        if (StringUtils.isNotBlank(AppIDGeneral)
            && StringUtils.isNotBlank(AppKeyGeneral)
            && StringUtils.isNotBlank(MasterGeneral)) {
            try {

                IGtPush push = new IGtPush(Host, AppKeyGeneral, MasterGeneral);
                IQueryResult abc = push.getClientIdStatus(AppIDGeneral, userId);

                String result = abc.getResponse().get("result").toString();

                if (result.equals("Online")) {// 推送非在线
                    online = true;
                }

            } catch (Exception e) {
                logger.error("{}", e);
            }
        }

        return online;

    }

}
